var express = require('express');
var router = express.Router();
var cookieParser = require('cookie-parser');
const bodyParser = require("body-parser");
const app = express();
app.use(bodyParser.json());
app.use(cookieParser());
var { User, Run, Coordinate, Friend } = require('../model/model')
const jwt = require("jsonwebtoken");

const SECRET = "secret"

const MY_ACCESS_TOKEN = "my_access_token"
const MY_REFRESH_TOKEN = "my_refresh_token"

const refreshTokenMap = new Map()
const multer = require("multer");
const fs = require("fs");


const upload = multer({
  dest: "uploads/",
});

//添加跑步记录
router.post("/addRun", async (req, res) => {
  await Run.create(req.body)
  //将新添加的跑步记录_id返回给前端
  let run = await Run.findOne(req.body)
  console.log(run);
  res.send({
    code: 200,
    msg: '添加成功',
  })
})
//修改跑步记录
router.put("/updateRun", async (req, res) => {
  //获取前端传递的id
  let _id = req.body.id
  //根据id修改跑步记录
  await Run.updateOne({ _id: _id }, req.body)
  res.send({
    code: 200,
    msg: '修改成功',
  })
})

//获取跑步记录
router.get("/getRun", async (req, res) => {
  let title = req.query.title
  //判断用户是否传递了标题
  if (!title) {
    //获取所有跑步记录
    let runs = await Run.find()
    res.send({
      code: 200,
      msg: '获取成功',
      runs
    })
  } else {
    //根据用户传递的标题获取跑步记录
    let runs = await Run.find({ title: title })
    res.send({
      code: 200,
      msg: '获取成功',
      runs
    })
  }
})
//获取坐标
router.get("/getzb", async (req, res) => {
  let { run } = req.query
  let zb = await Coordinate.find({ run: run })
  res.send({
    code: 200,
    msg: "获取成功",
    zb
  })
})
//添加坐标
router.post("/addzb", async (req, res) => {
  //添加坐标
  await Coordinate.create(req.body)
  res.send({
    code: 200,
    msg: "添加成功",
  })
})


router.post("/upload", upload.single("file"), (req, res) => {
  // 获取文件信息
  const file = req.file;
  // 获取切片文件名称
  let filename = req.body.filename;
  filename = filename.slice(0, filename.length - 4);
  // 获取切片文件索引值
  const index = req.body.index;
  // 配置切片文件的路径 uploads/文件名
  const chunkDir = `uploads/${filename}`;
  // 判断切片文件路径是否存在，不存在进行创建文件夹
  if (!fs.existsSync(chunkDir)) {
    fs.mkdirSync(chunkDir);
  }
  // 配置切片文件路径文件夹下的索引文件   uploads/文件名/0
  const chunkPath = `${chunkDir}` + "/" + `${index}`;
  // 将切片文件的名称 移动到 现在文件路径
  fs.renameSync(file.path, chunkPath);
  res.send("Chunk uploaded successfully");
});

router.post("/merge", (req, res) => {
  // 获取文件名称
  let { filename } = req.body;
  const fileType = filename.slice(filename.lastIndexOf(".") + 1);
  filename = filename.slice(0, filename.length - 4);
  // 视频文件夹路径
  const chunkDir = `uploads/${filename}`;
  // 视频合成完的路径
  const filePath = `uploads/${filename}.` + fileType;

  // 读取文件夹中的所有索引的切片文件 并排序
  const chunks = fs.readdirSync(chunkDir);
  chunks.sort((a, b) => a - b);

  // 遍历切片文件
  chunks.forEach((chunk, index) => {
    // 获取切片文件夹下的切片文件路径
    const chunkPath = `${chunkDir}/${chunk}`;
    // 将切片文件追加到 新文件 末尾
    fs.appendFileSync(filePath, fs.readFileSync(chunkPath));
    // 删除切片文件路径
    fs.unlinkSync(chunkPath);
  });
  // 删除文件夹
  fs.rmdirSync(chunkDir);
  res.send({
    filePath: 'http://localhost:3000/' + filePath,
    code: 200,
    message: "文件合并完成"
  });
});



router.get('/getData', async (req, res) => {
  let data = await Friend.find()
  res.send({
    data,
    code: 200,
    msg: "获取成功"
  })
})


router.post('/addFriend', async (req, res) => {
  let infos = await Friend.findOne({ _id: req.body.fid })
  await Friend.create({
    files: req.body.files,
    content: req.body.content,
    name: infos.name,
    uid: infos.uid,
    date: new Date(),
    lovenum: 0,
    logs: [],
    photo: infos.photo,
    address: infos.address,
  })
  res.send({
    code: 200,
    msg: "添加成功"
  })
})
router.get("/", (req, res) => {
  const accessToken = req.cookies[MY_ACCESS_TOKEN]
  if (!accessToken) {
    return res.status(401).send("no access token")
  }
})
router.post("/register", (req, res) => {
  res.send({
    code: 200,
    msg: "添加成功"
  })
})
router.post('/login', async (req, res) => {
  const { user, password } = req.body
  let finduser = await User.find({ name: user })
  let fid = finduser[0].fid
  // if(password===finduser[0].password){
  const accessToken = jwt.sign({ user }, SECRET, { expiresIn: 7200 })
  const refreshToken = jwt.sign({ user }, SECRET, { expiresIn: 86400 })

  const refreshTokens = refreshTokenMap.get(user) || [];
  refreshTokens.push(refreshToken)
  refreshTokenMap.set(user, refreshTokens)

  res.cookie(MY_ACCESS_TOKEN, accessToken, {
    httpOnly: true,
    secure: true,
    sameSite: "strict",
    maxAge: 1000 * 1000
  });
  res.cookie(MY_REFRESH_TOKEN, refreshToken, {
    httpOnly: true,
    secure: true,
    sameSite: "strict",
    maxAge: 3000 * 1000,
  });
  return res.send({
    code: 200,
    msg: "登录成功",
    fid,
  })


})

router.get("/refresh", (req, res) => {
  const refreshToken = req.cookies[MY_REFRESH_TOKEN];
  if (!refreshToken) {
    return res.status(403).send("no refresh token")
  }

  try {
    const { user } = jwt.verify(refreshToken, SECRET);
    const accessToken = jwt.sign({ user }, SECRET, { expiresIn: 7200 });
    res.cookie(MY_ACCESS_TOKEN, accessToken, {
      httpOnly: true,
      secure: true,
      sameSite: "strict",
      maxAge: 30 * 1000
    });
    return res.status(200).send("Refeshed")
  }
  catch (error) {
    res.clearCookie(MY_REFRESH_TOKEN);
    return res.res.status(403).send("no refresh token")
  }
})

router.use((req, res, next) => {
  const accessToken = req.cookies[MY_ACCESS_TOKEN];
  if (!accessToken) {
    return res.status(401).send("no access token")
  }
  try {
    const user = jwt.verify(accessToken, SECRET);
    res.locals.user = user
    return next()
  } catch (error) {
    res.clearCookie(MY_ACCESS_TOKEN);
    return res.status(401).send("Unauthorized")
  }
})

router.get("/profile", (req, res) => {
  const { user } = res.locals.user;
  return res.send(`Welcome ${user}`)
});


app.listen(() => {
  console.log('Server is running on port');
});





// module.exports = app;
module.exports = router;


